package com.geek.config.microprofile.source;

import org.eclipse.microprofile.config.spi.ConfigSource;

import javax.servlet.ServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ServletRequestConfigSource implements ConfigSource {

  private final ServletRequest servletRequest;
  private final String name;

  public ServletRequestConfigSource(final ServletRequest servletRequest) {
    this(servletRequest, null);
  }

  public ServletRequestConfigSource(final ServletRequest servletRequest, final String name) {
    this.servletRequest = servletRequest;
    this.name = name;
  }

  @Override
  public Set<String> getPropertyNames() {
    final Enumeration<String> names = servletRequest.getParameterNames();
    final Set<String> set = new HashSet<>();
    while (names.hasMoreElements()) {
      String s =  names.nextElement();
      set.add(s);
    }
    return set;
  }

  @Override
  public String getValue(String s) {
    return Stream.of(servletRequest.getParameterValues(s))
            .collect(Collectors.joining(","));
  }

  @Override
  public String getName() {
    return this.name;
  }
}
